package br.com.sig.faces;

import java.io.Serializable;
import java.util.Iterator;
import java.util.ResourceBundle;

import javax.enterprise.event.Observes;
import javax.faces.application.FacesMessage;
import javax.faces.event.PhaseEvent;

import org.jboss.seam.faces.event.qualifier.Before;
import org.jboss.seam.faces.event.qualifier.RenderResponse;

/**
 * Observer do Render Response
 *
 */
public class PhaseEventObserver implements Serializable {

	private static final long serialVersionUID = 8580889147674211934L;

	public void before(@Observes @Before @RenderResponse PhaseEvent event) {

		if (event.getFacesContext().isValidationFailed()) {
			FacesMessage requiredField = null;
			Iterator<FacesMessage> messages = event.getFacesContext().getMessages();
			
			ResourceBundle bundle = event.getFacesContext().getApplication().getResourceBundle(event.getFacesContext(), "messages");
			String message = bundle.getString("javax.faces.component.UIInput.REQUIRED");
			
			while (messages.hasNext()) {
				FacesMessage facesMessage = (FacesMessage) messages.next();			
				if (facesMessage.getSummary().equals(message)) {
					if (requiredField != null) {
						messages.remove();
					}
					requiredField = facesMessage;				
				}			
			}
		}
	}
}